package com.uniapp.server.service.impl;

import com.uniapp.server.model.RecordEntity;
import com.uniapp.server.repository.RecordRepository;
import com.uniapp.server.service.RecordService;
import com.uniapp.server.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author cyt
 * @describe
 * @create 2021-01-15 23:47
 */
@Service
public class RecordServiceImpl implements RecordService {

    @Autowired
    private RecordRepository recordRepository;

    @Override
    public ArrayList<RecordEntity> getByCreateTime(String time) {
        ArrayList<RecordEntity> all = recordRepository.findAll(getSpecification(time));
        return all;
    }

    private Specification<RecordEntity> getSpecification(String createdAt) {

        return (root, query, builder) -> {
            List<Predicate> predicateList = new ArrayList<>();

            if (!StringUtils.isEmpty(createdAt)) {
                predicateList.add(builder.greaterThanOrEqualTo(root.get("createTime").as(String.class), createdAt));
                predicateList.add(builder.lessThanOrEqualTo(root.get("createTime").as(String.class),
                        DateUtil.beforeStringDate(createdAt, 1, "yyyy-MM-dd")));
            }
            return builder.and(predicateList.toArray(new Predicate[0]));
        };
    }

    @Override
    public Page<RecordEntity> getPage(Integer page, Integer size) {
        Page<RecordEntity> all = recordRepository.findAll(getPageable(page, size));
        return all;
    }

    @Override
    public void add(RecordEntity recentlyEntity) {
        recordRepository.save(recentlyEntity);
    }

    @Override
    public void deleteById(Integer id) {
        recordRepository.deleteById(id);
    }

    @Override
    public RecordEntity getById(Integer id) {
        return recordRepository.findById(id).get();
    }

    @Override
    public void update(RecordEntity recordEntity) {
        recordRepository.save(recordEntity);
    }

    static Pageable getPageable(Integer page, Integer size) {
        return PageRequest.of(
                page - 1, size,
                Sort.by(Sort.Direction.ASC, "id")
        );
    }
}
